package com.tanhua.management.service;


import cn.hutool.core.convert.Convert;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.api.MomentsApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Video;

import com.tanhua.management.vo.VideoVo;
import com.tanhua.management.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class VideoService {

    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    @Reference(version = "1.0.0")
    private MomentsApi momentsApi;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    /**
     *      视频管理
     *          视频记录翻页
     * @param page  页尺寸
     * @param pageSize 页数
     * @param sortProp 排序字段
     * @param sortOrder ascending 升序 descending 降序
     * @param uid 用户ID
     * @return
     */
    public PageResult queryVideoList(Integer page, Integer pageSize, String sortProp, String sortOrder, Integer uid) {
        // 1. 通过用户id查询小视频列表
        List<Video> videoList = videoApi.queryVideosList(uid);
        //2.查询用户信息表,为每个视频填充用户信息
        // 2.1 获取用户id集合(Set集合防止用户id重复)
        Set<Long> userIds = videoList.stream().map(Video::getUserId).collect(Collectors.toSet());
        // 2.2 查询用户信息的集合
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserInfo::getUserId, userIds);
        List<UserInfo> userInfoList = userInfoMapper.selectList(queryWrapper);


        // 3. 封装pageResult对象并给其部分属性赋值
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);//当前页码
        pageResult.setPagesize(pageSize);//页大小
        pageResult.setCounts(videoList.size());//总条数
        Integer pageTotalNum = videoList.size() % pageResult.getPagesize() == 0 ? videoList.size() / pageResult.getPagesize() : videoList.size() / pageResult.getPagesize() + 1;
        pageResult.setPages(pageTotalNum);//总页数

        // 4. new一个集合来接返回给前端的vo
        List<VideoVo> videoVoList = new ArrayList<>();

        // 5. 遍历得到的是视频列表,给返回前端的VideoVo的属性赋值
        for (Video video : videoList) {
            VideoVo videoVo = new VideoVo();
            videoVo.setId(video.getVid().intValue());  // 编号
            videoVo.setUserId(video.getUserId().intValue()); // 发布人id
            Integer date = Integer.valueOf(String.valueOf(new SimpleDateFormat("yyyyMMdd")
                    .format(video.getCreated())));// 把日期转成指定格式的Integer类型
            videoVo.setCreateDate(date);   // 发布时间
            videoVo.setVideoUrl(video.getVideoUrl()); // 视频链接
            videoVo.setPicUrl(video.getPicUrl()); // 封面图片


            // 5.1 获取点赞数
              Long likeCount = momentsApi.findLikeCount(video.getId().toHexString());
              videoVo.setLikeCount(likeCount.intValue());

            // 5.2 获取评论数
            Long commentCount = momentsApi.findCommentCount(video.getId().toHexString());
            videoVo.setCommentCount(commentCount.intValue());

            // 5.3 获取举报数
            Integer repoertCount = momentsApi.findVideoRepoertCount(video.getId().toHexString());
            videoVo.setReportCount(repoertCount);//举报数
//            videoVo.setReportCount(new Random().nextInt(500));

            // 5.4 获取转发数
            Integer forwardCount = momentsApi.findVideoForwardCount(video.getId().toHexString());
            videoVo.setForwardingCount(forwardCount);//转发数
//            videoVo.setForwardingCount(new Random().nextInt(500));//转发数


            // 5.5遍历用户信息集合,给
            for (UserInfo userInfo : userInfoList) {
                // 5.5.1通过视频对象得到用户id对应上用户信息中的用户id,给videoVo赋值昵称,并把符合条件的videoVo封装到集合
                if (video.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    videoVo.setNickname(userInfo.getNickName());
                    videoVoList.add(videoVo);

                }
            }

        }


        // 6. 排序
        Collections.sort(videoVoList, (o1, o2) -> {
            int result = 0;
            switch (sortProp) {
                case "reportCount": {
                    result = o1.getReportCount() - o2.getReportCount();
                    break;
                }
                case "likeCount": {
                    result = o1.getLikeCount() - o2.getLikeCount();
                    break;
                }
                case "commentCount": {
                    result = o1.getCommentCount() - o2.getCommentCount();
                    break;
                }
                case "forwardingCount": {
                    result = o1.getForwardingCount() - o2.getForwardingCount();
                    break;
                }
                case "createDate": {
                }
                default: {
                    result = (int) (o1.getCreateDate() - o2.getCreateDate());
                    break;
                }
            }
            if ("descending".equals(sortOrder)) {
                result = -result;
            }
            return result;
        });

        // 7. 分页
        List<VideoVo> newVideoVos = new ArrayList<>();
        int startIndex = (page - 1) * pageSize;
        if (startIndex < videoVoList.size()) {
            int endIndex = startIndex + pageSize - 1;
            if (endIndex >= videoVoList.size()) {
                endIndex = videoVoList.size() - 1;
            }

            newVideoVos = videoVoList.subList(startIndex, endIndex + 1);
        }
        // 8. 给pageResult的items集合赋值
        pageResult.setItems(newVideoVos);
        return pageResult;

    }

}
